package com.nit;

import com.nit.generate.NitChineseNameGenerator;
import com.nit.generate.NitIdcardGenerator;
import com.nit.generate.NitJobGenerator;
import com.nit.generate.NitUUIDGenerator;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 百万CSV数据生成示例
 *
 * @Auth：逆天开源-逍遥哥哥
 * @Date：2023-07-17
 */
public class CSVMain {
    public static void main(String[] args) {
        CSVMain.write();
    }

    public static void write() {

        ExecutorService executorService = Executors.newFixedThreadPool(100);

        try (CSVPrinter printer = new CSVPrinter(new FileWriter("百万.csv"), CSVFormat.DEFAULT)) {
            String title[] = new String[]{"uuid", "姓名", "身份证号", "职业"};
            printer.printRecord(title);

            Long start = System.currentTimeMillis();
            List<Future> futureList = new ArrayList<>(1000000);
            for (int i = 0; i < 1000000; i++) {
                Future future = executorService.submit(() -> {
                    String uuid = NitUUIDGenerator.generate();
                    String name = NitChineseNameGenerator.generate();
                    String idCard = NitIdcardGenerator.generate();
                    String job = NitJobGenerator.generate();
                    try {
                        printer.printRecord(uuid, name, idCard, job);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return "ok";
                });
                futureList.add(future);
            }

            for (Future futureTmp : futureList) {
                futureTmp.get();
            }
            Long end = System.currentTimeMillis();
            long time = end - start;
            System.out.println("百万执行耗时：" + time + "毫秒");
//            executorService.shutdown();
//            百万单线程执行耗时：16478毫秒
//            百万多线程执行耗时：9725毫秒
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
